package com.halflife.nio;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO
 * A Thead per Connection;
 * blocking 10000
 * 一个线程大约1M； 还有很多blocking。
 * 内核发生了一些变化===》允许NIO模式  非阻塞 用轮询
 */
public class MutiSocketIO {
    public static void main(String[] args) throws Exception{
        /**
         * systemcall::
         * socket()=6fd
         * bind(6fd,9090)
         * listen(6fd)
         */
        ServerSocket serverSocket = new ServerSocket(9090);
        System.out.println("step1: new ServerSocket"+serverSocket.toString());
        while (true) {
            /**
             * systemcall::
             * accept(6fd)===blocking==>7fd   blocking......
             * nio no blocking
             */
            Socket client = serverSocket.accept();
            System.out.println("step2: new Socket"+client.getRemoteSocketAddress().toString()+"/"+client.getPort()+"/"+client.getLocalPort());
            Thread thread = new Thread(() -> {
                try {
                    /**
                     * blocking.......
                     * read(7fd)
                     * client.getInputStream();
                     * nio no blocking;
                     *
                     * private int socketRead(FileDescriptor fd,
                     *                            byte b[], int off, int len,
                     *                            int timeout)
                     *         throws IOException {
                     *         return socketRead0(fd, b, off, len, timeout);
                     *     }
                     */
                    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    String result = null;
                    int limit = 0;

                    while ((result = br.readLine()) != null) {
                        System.out.println(result);
                        limit++;
                        if (limit >= 3) {
                            client.getOutputStream().write("OK!".getBytes());
                            client.getOutputStream().close();
                            br.close();
                            client.close();
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }

    }
}

